package com.lzclass.util;

import com.lzclass.pojo.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    private static final long passTime = 60000*60*24;//过期时间 24小时

    private static final String key = "laozhangshuaidehen"; // 密钥

    private static final String pre = "lzclass";//令牌

    private static final String saobao = "eft09a";

    public static String  getToken(User user){
        String token = Jwts.builder().setSubject(pre)
                .claim("uid",user.getUid())
                .claim("username",user.getUsername())
                .setIssuedAt(new Date())//发布时间
                .setExpiration(new Date(System.currentTimeMillis()+passTime))//过期时间
                .signWith(SignatureAlgorithm.HS256,key).compact();
        return saobao+token;
    }
    public static Map<String, Object> checkToken(String token){
        Map<String,Object> map = new HashMap<>();

        try{
            final Claims claims = Jwts.parser().setSigningKey(key)
                    .parseClaimsJws(token.replace(saobao,"")).getBody();
            map.put("state","OK");
            map.put("info",claims);
            return map;
        }catch (Exception e){
            map.put("state","error");
            if(e.toString().indexOf("ExpiredJwtException")>0){
                map.put("info","过期");
            }else{
                map.put("info","未登录");
            }

            return map;
        }
    }




}
